﻿using HomagGroup.Base.UI.Windows;
using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;

namespace HomagChina.CCHCS.Views
{
    /// <summary>
    /// Taskqueue.xaml 的交互逻辑
    /// </summary>
    public partial class StockInfo : Dialog
    {
        private double HomeBatchDetailVerticalOffset;

        public StockInfo()
        {
            InitializeComponent();
        }

        public void ViewModel_RequestScrollPositionSave(object sender, EventArgs e)
        {
            SaveScrollPosition();
        }

        public void ViewModel_RequestScrollPositionRestore(object sender, EventArgs e)
        {
            RestoreScrollPosition();
        }

        private void SaveScrollPosition()
        {
            var BatchDetailscrollViewer = VisualTreeHelperExtensions.FindVisualChild<ScrollViewer>(TableStockInfo);
            if (BatchDetailscrollViewer != null)
            {
                HomeBatchDetailVerticalOffset = BatchDetailscrollViewer.VerticalOffset;
            }
        }

        private void RestoreScrollPosition()
        {
            var BatchDetailscrollViewer = VisualTreeHelperExtensions.FindVisualChild<ScrollViewer>(TableStockInfo);
            BatchDetailscrollViewer?.ScrollToVerticalOffset(HomeBatchDetailVerticalOffset);
        }

        public static class VisualTreeHelperExtensions
        {
            public static T FindVisualChild<T>(DependencyObject parent) where T : DependencyObject
            {
                if (parent == null) return null;

                for (int i = 0; i < VisualTreeHelper.GetChildrenCount(parent); i++)
                {
                    var child = VisualTreeHelper.GetChild(parent, i);
                    if (child is T foundChild)
                    {
                        return foundChild;
                    }
                    var childOfChild = FindVisualChild<T>(child);
                    if (childOfChild != null)
                    {
                        return childOfChild;
                    }
                }
                return null;
            }
        }
    }
}